/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\SystemSettings\GeneralConfig\component\AogtimesConfigSetting\index.tsx
 * @Date: 2022-03-16 16:38:17
 * @LastEditTime: 2023-08-07 18:25:02
 */
import UdSelect from '@/components/UdFormControls/UdSelect'
import { columnRenders, http, IUdColumn, UdFilter, UdModal, UdTable, UdToolbar } from '@/lib'
import { Button, message, Modal, Tooltip } from 'antd'
import React, { PureComponent } from 'react'
import AddHanderForm from './components/AddHanderForm'
import apis from '@/apis/SystemSettings'
import dayjs from 'dayjs'
// import { getSessionStorage, setSessionStorage } from '@/utils/methods'
type Props = {
  brandList: ReadonlyArray<any>
}

type State = {
  conditions: any[]
  loading: boolean
  page: number
  size: number
  total: number
  dataSource: any[]
}

/** 新增经济业务项目入参 */
type EB_Params = {

  id?: number
  [Key: string]: any
}



export default class AogtimesConfigSetting extends PureComponent<Props, State> {
  private filterForm: any
  private brandList: ReadonlyArray<any> = this.props.brandList
  state: State = {
    conditions: [
      {
        label: '品牌公司',
        id: 'brandCode',
        initialValue: this.brandList[0].value,
        render: <UdSelect showSearch allowClear={false} options={this.brandList} />,
      },
    ],
    loading: false,
    page: 1,
    size: 10,
    total: 0,
    dataSource: [],
  }
  columns: IUdColumn<any>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: '50px',
      render: (text, reoled, index) => index + 1,
    },
    {
      title: '品牌公司',
      dataIndex: 'dataKey',
      align: 'center',
      key: 'dataKey',
      width: '230',
      render: (text, record) => {
        return (
          <Tooltip title={text}>
            <div style={{ width: '100%', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
              {text}
            </div>
          </Tooltip>
        )
      },
    },
    {
      title: '取数类型',
      dataIndex: 'dataType',
      key: 'dataType',
      width: '160px',
      render: (text, record) => {
        return  record.dataType == 'customBillTime' ? '特殊期间开单' : '盘点时间'
      },
    },
    {
      title: '取数周期',
      dataIndex: 'dataValue',
      align: 'center',
      key: 'dataValue',
      minWidth: '200px',
      render: (text, record) => {
        let dateArr = record.dataValue.split('~')
        return (
          <Tooltip title={record.dataValue}>
            <div style={{ width: '100%', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
              {record.dataType === 'customBillTime'?`${ dayjs(dateArr[0]).format('YYYY-MM-DD 00:00:00')}~${ dayjs(dateArr[1]).format('YYYY-MM-DD 23:59:59')}`:record.dataValue}
            </div>
          </Tooltip>
        )
      },
    },
    {
      title: '是否开启特殊期间开单',
      dataIndex: 'isOpen',
      key: 'isOpen',
      width: '160px',
      render: (text, record) => {
        return  record.dataType == 'customBillTime' ? (text == 'ON' ? '打开' : '关闭') : '-'
      },
    },
    {
      title: '是否盘点上月',
      dataIndex: 'isCheck',
      key: 'isCheck',
      width: '160px',
      render: (text, record) => {
        return  record.dataType == 'nowAogTimes' ? (text == 'Y' ? '是' : '否') : '-'
      },
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: '160px',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      fixed: 'right' as 'right',
      width: 130,
      render: columnRenders.operate([
        {
          title: '编辑',
          action: (text: any, record: any) => {
            this.handerDrawer(record)
          },
        },
        {
          title: '删除',
          action: (text: any, record: any) => {
            Modal.confirm({
              title: '删除',
              content: `确定删除【${record.dataKey}】此项配置吗`,
              okType: 'danger',
              onOk: () => {
                return this.handDeleteEconomicBusiness(record)
              },
            })
          },
        },
      ]),
    },
  ]

  componentDidMount(): void {
    this.getRecordTableData()

  }



  private handleSearch = (values: any) => {
    this.setState({ page: 1 }, () => {
      this.getRecordTableData()
    })
  }

  private resetFilterHandle = form => {
    this.setState(
      {
        dataSource: [],
        page: 1,
        total: 0,
      },
      () => {
        this.getRecordTableData()
      }
    )
  }

  private handleChangePage = pagination => {
    const { current: page, pageSize: size } = pagination
    this.setState({ page, size }, () => {
      this.getRecordTableData()
    })
  }

  private getRecordTableData = async () => {
    this.setState({ loading: true })
    try {
      let list: any = await http.post(apis.getNowAogTimesPage, {
        page: this.state.page,
        size: this.state.size,
        conditions: this.filterForm.getFieldsValue(),
      })
      const dataSource = list.data?.content
      this.setState({
        dataSource,
        total: list.data.totalElements,
        loading: false,
      })
    } catch (error) {
      this.setState({
        loading: false,
      })
    }
  }



  private handUpdateEconomicBusiness = (params: EB_Params) => {
    if(params.dataType=='nowAogTimes'){
      delete params.isOpen
    }else{
      delete params.isCheck
      params.dataValue = params.dataStartValue + "~" + params.dataEndValue
    }
    return http
      .post(apis.addOrUpdateNowAogTimes, params)
      .then(() => {
        message.success('编辑成功')
        this.getRecordTableData()
      })
      .catch(() => {
        return Promise.reject()
      })
  }

  private handDeleteEconomicBusiness = (params: EB_Params) => {
    return http
      .post(apis.addOrUpdateNowAogTimes, {...params,del:'Y' })
      .then(() => {
        message.success('删除成功')
        this.getRecordTableData()
      })
      .catch(() => {
        return Promise.reject()
      })
  }

  private handerDrawer = (data?: object) => {
    UdModal.open({
      title: data ? '编辑' : '新增',
      width: '60%',
      content: <AddHanderForm  data={data} brandList={this.props.brandList} />,
      okText: '确定',
      cancelText: '取消',
      onOk: values => {
        if(data) {
          values['id'] = data['id']
        }
        //values['dataValue'] = values.dataStartValue+"~"+values.dataEndValue;
        return this.handUpdateEconomicBusiness(values) 
      },
    })
  }

  render() {
    const { loading, page, size, total, dataSource, conditions } = this.state
    return (
      <>
        <UdFilter
          items={conditions}
          onSearch={values => {
            this.handleSearch(values)
          }}
          getForm={form => {
            this.filterForm = form
          }}
          loading={this.state.loading}
          resetAfter={this.resetFilterHandle}
        />
        <UdToolbar
          other={
            <Button
              type="primary"
              onClick={() => {
                this.handerDrawer()
              }}
            >
              新增
            </Button>
          }
        ></UdToolbar>
        <UdTable
          rowKey="id"
          loading={loading}
          columns={this.columns}
          dataSource={dataSource}
          onChange={this.handleChangePage}
          scroll={{ x: true }}
          pagination={{
            current: page,
            pageSize: size,
            total: total,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '30', '40'],
            showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
          }}
        ></UdTable>
      </>
    )
  }
}
